package com.example.springsecuritydemo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author 朱学鑫
 * @projectName springSecurity-Demo
 * @description: Security配置类 第三种方式
 * @date 2022年02月22日 16:58
 */
@Configuration
public class SecurityConfig2 extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(password());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()// 自己编写的登录页面
                .loginPage("/login.html") // 登录页面设置
                .loginProcessingUrl("/user/login")// 登录访问路径
                .defaultSuccessUrl("/test/index").permitAll()//登录成功跳转路径
                .and().authorizeRequests()
                .antMatchers("/","/test/hello","/user/login","/swagger-ui/**").permitAll() //设置哪些路径不需要认证直接访问
                .anyRequest().authenticated()
                .and().csrf().disable(); // 关闭csrf防护
    }

    /**
     * 表示把参数按照特定的解析规则进行解析
     * @return
     */
    @Bean
    PasswordEncoder password() {
        return new BCryptPasswordEncoder();
    }

}
